# views/viewer.py

import os
import logging
from PyQt5.QtWidgets import (
    QWidget, QLabel, QPushButton, QHBoxLayout, QVBoxLayout, QFileDialog, QCheckBox, QMessageBox
)
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt
from utils.keyboard_shortcuts import KeyboardShortcuts

class Viewer(QWidget):
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window

        # 初始化变量
        self.image_files = []
        self.current_index = 0
        self.total_images = 0
        self.favorites = self.main_window.favorites
        self.thumbnail_size = 100
        self.processed_images = set()

        # 创建控件
        self.create_widgets()

        # 设置焦点策略，并给予焦点以接收键盘事件
        self.setFocusPolicy(Qt.StrongFocus)
        self.setFocus()

    def create_widgets(self):
        layout = QVBoxLayout(self)

        # 显示图片的标签
        self.image_label = QLabel("请打开或拖入图片文件夹")
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setMinimumSize(400, 400)
        layout.addWidget(self.image_label, stretch=1)

        # 控制按钮
        controls_layout = QHBoxLayout()

        prev_button = QPushButton("上一张")
        prev_button.clicked.connect(self.previous_image)
        controls_layout.addWidget(prev_button)

        next_button = QPushButton("下一张")
        next_button.clicked.connect(self.next_image)
        controls_layout.addWidget(next_button)

        self.favorite_button = QPushButton("收藏")
        self.favorite_button.clicked.connect(self.toggle_favorite)
        controls_layout.addWidget(self.favorite_button)

        self.image_counter = QLabel("图片 0 / 0")
        controls_layout.addWidget(self.image_counter)

        controls_layout.addStretch()

        layout.addLayout(controls_layout)

        # 图片目录选择
        dir_layout = QHBoxLayout()
        dir_label = QLabel("图片目录：")
        dir_layout.addWidget(dir_label)

        self.dir_line_edit = QLabel(self.main_window.directory)
        dir_layout.addWidget(self.dir_line_edit)

        browse_button = QPushButton("浏览")
        browse_button.clicked.connect(self.browse_folder)
        dir_layout.addWidget(browse_button)

        load_button = QPushButton("加载图片")
        load_button.clicked.connect(self.load_images)
        dir_layout.addWidget(load_button)

        self.auto_update_checkbox = QCheckBox("自动更新图片")
        self.auto_update_checkbox.setChecked(self.main_window.auto_update)
        self.auto_update_checkbox.stateChanged.connect(self.toggle_auto_update)
        dir_layout.addWidget(self.auto_update_checkbox)

        dir_layout.addStretch()

        layout.addLayout(dir_layout)

    def browse_folder(self):
        directory = QFileDialog.getExistingDirectory(self, "选择图片目录", self.main_window.directory)
        if directory:
            self.main_window.directory = directory
            self.dir_line_edit.setText(self.main_window.directory)
            self.load_images()

    def load_images(self):
        directory = self.main_window.directory
        if not os.path.isdir(directory):
            self.image_label.setText("请打开或拖入图片文件夹")
            self.image_counter.setText("图片 0 / 0")
            logging.warning("加载图片失败：目录不存在。")
            return

        self.image_files = []
        for filename in os.listdir(directory):
            if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')):
                image_path = os.path.join(directory, filename)
                self.image_files.append(image_path)

        self.total_images = len(self.image_files)
        if self.total_images == 0:
            self.image_label.setText("目录中没有找到图片文件。")
            self.image_counter.setText("图片 0 / 0")
            logging.info("加载图片完成：目录中没有图片文件。")
            return

        self.current_index = 0
        self.processed_images = set(os.listdir(directory))
        self.update_image()
        self.main_window.save_settings()
        self.main_window.gallery.load_images()
        self.main_window.favorites_view.load_favorites()
        logging.info(f"加载了 {self.total_images} 张图片。")

    def update_image(self):
        if self.total_images == 0:
            self.display_placeholder()
            return

        image_path = self.image_files[self.current_index]
        if not os.path.isfile(image_path):
            self.image_label.setText("图片文件不存在。")
            logging.error(f"图片文件不存在：{image_path}")
            return

        image = QImage(image_path)
        if image.isNull():
            self.image_label.setText("无法加载图片。")
            logging.error(f"无法加载图片：{image_path}")
            return

        pixmap = QPixmap.fromImage(image)
        self.image_label.setPixmap(pixmap.scaled(
            self.image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

        self.update_image_counter()
        self.update_favorite_button()
        logging.info(f"显示图片：{image_path}")

    def display_placeholder(self):
        self.image_label.setText("请打开或拖入图片文件夹")
        self.image_label.setPixmap(QPixmap())
        self.image_counter.setText("图片 0 / 0")
        self.favorite_button.setEnabled(False)
        logging.info("显示占位符：请打开或拖入图片文件夹。")

    def resizeEvent(self, event):
        self.update_image_size()
        super().resizeEvent(event)

    def update_image_size(self):
        if self.total_images == 0:
            return
        image_path = self.image_files[self.current_index]
        image = QImage(image_path)
        if image.isNull():
            return
        pixmap = QPixmap.fromImage(image)
        self.image_label.setPixmap(pixmap.scaled(
            self.image_label.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))

    def previous_image(self):
        if self.total_images == 0:
            return
        self.current_index = (self.current_index - 1) % self.total_images
        self.update_image()
        logging.info(f"切换到上一张图片，当前索引：{self.current_index}")

    def next_image(self):
        if self.total_images == 0:
            return
        self.current_index = (self.current_index + 1) % self.total_images
        self.update_image()
        logging.info(f"切换到下一张图片，当前索引：{self.current_index}")

    def toggle_favorite(self):
        if self.total_images == 0:
            return
        image_path = self.image_files[self.current_index]
        if image_path in self.favorites:
            self.favorites.remove(image_path)
            logging.info(f"取消收藏图片：{image_path}")
        else:
            self.favorites.add(image_path)
            logging.info(f"收藏图片：{image_path}")
        self.update_favorite_button()
        self.main_window.save_settings()
        self.main_window.favorites_view.load_favorites()

    def update_favorite_button(self):
        if self.total_images == 0:
            self.favorite_button.setEnabled(False)
            return
        self.favorite_button.setEnabled(True)
        image_path = self.image_files[self.current_index]
        if image_path in self.favorites:
            self.favorite_button.setText("取消收藏")
        else:
            self.favorite_button.setText("收藏")

    def update_image_counter(self):
        self.image_counter.setText(f"图片 {self.current_index + 1} / {self.total_images}")

    def clear_image(self):
        self.image_label.clear()
        self.image_label.setText("请打开或拖入图片文件夹")
        self.image_counter.setText("图片 0 / 0")

    def toggle_auto_update(self):
        self.auto_update = self.auto_update_checkbox.isChecked()
        self.main_window.auto_update = self.auto_update
        if self.auto_update:
            self.main_window.start_watching_directory()
            logging.info("启用自动更新图片。")
        else:
            self.main_window.stop_watching_directory()
            logging.info("禁用自动更新图片。")
        self.main_window.save_settings()

    def keyPressEvent(self, event):
        shortcuts = KeyboardShortcuts()
        if event.key() == shortcuts.PREVIOUS_IMAGE:
            self.previous_image()
        elif event.key() == shortcuts.NEXT_IMAGE:
            self.next_image()
        elif event.key() == shortcuts.TOGGLE_FAVORITE:
            self.toggle_favorite()
        elif event.key() == shortcuts.OPEN_FOLDER_KEY and (event.modifiers() & shortcuts.OPEN_FOLDER_MODIFIERS):
            self.browse_folder()
        else:
            super().keyPressEvent(event)

    # 拖放事件处理
    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()

    def dropEvent(self, event):
        urls = event.mimeData().urls()
        if urls:
            directory = urls[0].toLocalFile()
            if os.path.isdir(directory):
                self.main_window.directory = directory
                self.main_window.save_settings()
                self.dir_line_edit.setText(self.main_window.directory)
                self.load_images()
                logging.info(f"通过拖放加载目录：{directory}")
            else:
                QMessageBox.warning(self, "无效的目录", "拖放的不是有效的文件夹路径。")
                logging.warning(f"无效的拖放目录：{directory}")
